﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WikiQuizz.Common.Interfaces;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace WikiQuizz.StandardImplementations
{
    public class PopulationFilter : IPopulationFilter
    {
        public string Filter(IEnumerable<XNode> rawData)
        {
            string result = ExtractCandidateNode(rawData);

            result = result.Replace("'", ".");

            if (result.Contains("Mio") || result.Contains("Million"))
            {
                return result;
            }
            else
            {
                Regex reg = new Regex(@"\d{1,}.\d{1,}.\d{1,}.\d{1,}");

                Match mat = reg.Match(result);
                if (mat.Success)
                {
                    return mat.ToString();
                }
                else
                {
                    return result;
                } 
            }
            
        }

        private string ExtractCandidateNode(IEnumerable<XNode> rawData)
        {
            var withoutSmall = (from o in rawData
                         where !o.ToString().Contains("<small")
                         select o);

            var withoutSup = (from o in withoutSmall
                              where !o.ToString().StartsWith("<sup")
                              select o);

            var withoutHRef = (from o in withoutSup
                               where !o.ToString().StartsWith("<a href")
                               select o);

            var withoutBr = (from o in withoutHRef
                             where !o.ToString().StartsWith("<br")
                             select o);

            var withoutAngleBrackets = (from o in withoutBr
                                        where !o.ToString().StartsWith("[")
                                        select o);

            var withoutBrackets = (from o in withoutAngleBrackets
                                       where !(o.ToString().StartsWith("(") && o.ToString().EndsWith(")"))
                                       select o);

            var withoutOnlyCloseBracket = (from o in withoutBrackets
                                          where !o.ToString().Equals(")")
                                          select o);

            var withoutOnlyOpenBracket = (from o in withoutOnlyCloseBracket
                                          where !o.ToString().Equals("(")
                                          select o);

            return withoutOnlyOpenBracket.FirstOrDefault().ToString();
        }
    }
}
